<template>
  <div id="homePage">
    <!-- 搜索框 -->
    <div class="search-bar">
      <a-input-search
        placeholder="从海量图片中搜索"
        v-model:value="searchParams.searchText"
        enter-button="搜索"
        size="large"
        @search="doSearch"
      />
    </div>
    <!-- 分类 + 标签 -->
    <a-tabs v-model:activeKey="selectedCategory" @change="doSearch">
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :key="category" :tab="category" />
    </a-tabs>
    <div class="tag-bar">
      <span style="margin-right: 8px">标签：</span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag"
          v-model:checked="selectedTagList[index]"
          @change="doSearch"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </div>
    <!-- 图片列表 -->
    <div class="picture-list">
      <a-list
        :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
        :data-source="dataList"
        :pagination="pagination"
        :loading="loading"
      >
        <template #renderItem="{ item: picture }">
          <a-list-item style="padding: 0">
            <!-- 单张图片 -->
            <a-card hoverable @click="doClickPicture(picture)">
              <template #cover>
                <img
                  style="height: 180px; object-fit: cover"
                  :alt="picture.name"
                  :src="picture.thumbnailUrl ?? picture.url"
                  loading="lazy"
                />
              </template>
              <a-card-meta :title="picture.name">
                <template #description>
                  <a-flex>
                    <a-tag color="green">
                      {{ picture.category ?? '默认' }}
                    </a-tag>
                    <a-tag v-for="tag in picture.tags" :key="tag">
                      {{ tag }}
                    </a-tag>
                  </a-flex>
                </template>
              </a-card-meta>
            </a-card>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  listPictureVoByPageUsingPost,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'

//图片数据列表
const dataList = ref([])
//数据的总数量
const total = ref(0)
//数据加载状态
const loading = ref(true)

// 搜索参数
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数对象
const pagination = computed(() => {
  return {
    // 当前页码
    current: searchParams.current ?? 1,
    // 每页显示数量
    pageSize: searchParams.pageSize ?? 10,
    // 数据总数量
    total: total.value,
    // 分页切换时的回调函数，接收新的页码和每页显示数量
    onChange: (page, pageSize) => {
      searchParams.current = page
      searchParams.pageSize = pageSize
      // 重新获取数据
      fetchData()
    },
  }
})

// 异步获取图片数据
const fetchData = async () => {
  // 加载状态设置为 true
  loading.value = true

  // 转换搜索参数
  const params = {
    ...searchParams,
    tags: [],
  }
  // 如果当前选中的分类不是 'all'，则将选中的分类添加到参数中
  if (selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }
  // 遍历当前选中的标签列表
  selectedTagList.value.forEach((useTag, index) => {
    // 如果当前标签不为空
    if (useTag) {
      // 将对应的标签从 tagList 中添加到参数的 tags 数组中
      params.tags.push(tagList.value[index])
    }
  })

  const res = await listPictureVoByPageUsingPost(params)

  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  //将加载状态设置为 false
  loading.value = false
}

// 页面挂载完成时调用
onMounted(() => {
  fetchData()
  getTagCategoryOptions()
})

const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  fetchData()
}

// 分类列表
const categoryList = ref<string[]>([])
//当前选中的分类
const selectedCategory = ref<string>('all')
//标签列表
const tagList = ref<string[]>([])
//当前选中的标签列表
const selectedTagList = ref<string[]>([])

// 获取标签和分类选项的函数
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()

  if (res.data.code === 0 && res.data.data) {
    // 分类列表赋值给 categoryList
    categoryList.value = res.data.data.categoryList ?? []
    // 标签列表赋值给 tagList
    tagList.value = res.data.data.tagList ?? []
  } else {
    message.error('加载分类标签失败，' + res.data.message)
  }
}
const router = useRouter()
// 跳转至图片详情
const doClickPicture = (picture) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}
</script>
<style lang="scss" scoped>
#homePage {
  .search-bar {
    max-width: 480px;
    margin: 0 auto 16px;
  }
  .picture-list {
    margin-top: 20px;
  }
}
</style>
